var prefix = "/userAunt";
let myDataList=[],myjazSysProjectList=[],myDataList1=[],myDataList2=[],myDataList3=[],myUser={}
layui.use(['form', 'xmSelect', 'upload', 'laydate'], function () {
    var form = layui.form;
    laydate = layui.laydate;
    // AjaxGet( '/userAunt/seleProject'  ).then(function (response){
    //     if(response.code=='0'){
    //         myjazSysProjectList=response.data
    //     }
    // }).catch(error => {
    //     layer.msg(error.msg)
    // })
    $('#mySelect').attr("disabled",true);
    AjaxGet( '/userAunt/getUserAunts'  ).then(function (response){
        if(response.code=='0'){
            myDataList=response.data
            //设置select
            $('#mySelect').empty();
            $('#mySelect').append($('<option>', {
                value: '',
                text: '请选择姓名'
            }))
            //没有的时候进行设置
            if(!myDataList.find(item=>item.sysUserid==$('#userId').val()) && $('#inputType').val()=='edit'){
                myDataList.push({
                    sysUserid:$('#userId').val(),
                    name:$('#nameValue').val(),
                    mobile:$('#phoneValue').val(),
                    sex:$('#sexValue').val(),
                    projectName:$('#projectNameValue').val(),
                    projectId:$('#projectIdValue').val(),
                })
            }
            myDataList.forEach(item=>{
                $('#mySelect').append($('<option>', {
                    value: item.sysUserid,
                    text: item.name+'-'+item.mobile,
                    selected:$('#userId').val()==item.sysUserid
                }))
            })
            $('#mySelect').attr("disabled",$('#inputType').val()=='edit');
            form.render('select');
            selectInput($('#mySelect'),10)
        }
    }).catch(error => {
        layer.msg(error.msg)
    })
    form.on('select(demo-select-filter)', function(data){
        var elem = data.elem; // 获得 select 原始 DOM 对象
        var value = data.value; // 获得被选中的值
        var othis = data.othis; // 获得 select 元素被替换后的 jQuery 对象
        if(data.value!=""){
            let item=myDataList.find((itemdata)=> itemdata.sysUserid==value)
            myUser=item;
            $('#phone').html(`<span>${item.mobile}</span>`)
            $('#sex').html(`<span>${item.sex== '1'?'男':'女'}</span>`)
            // $('#jazSysProject').html(`<span>${item.projectName}</span>`)
        }else {

            $('#phone').html(`<span>请选择姓名</span>`)
            $('#sex').html(`<span>请选择姓名</span>`)
            // $('#jazSysProject').html(`<span>请选择姓名</span>`)
        }
    });

    //小区

    const setMySelect2=(name)=>{
        //设置mySelect2
        myDataList2=myDataList1.find((itemdata)=> itemdata.name==name)
        myDataList2=myDataList2.buildNumberList
        //设置select
        $('#mySelect2').empty();
        $('#mySelect2').append($('<option>', {
            value: '',
            text: '请选择楼栋房号'
        }))
        myDataList2.forEach(item=>{
            $('#mySelect2').append($('<option>', {
                value: item.name,
                text: item.name,
                selected:$('#buildNumber').val()==item.name
            }))
        })
        $('#mySelect2').attr("disabled",false);
        form.render('select');
        selectInput($('#mySelect2'),10)
        if($('#inputType').val()=='edit'){
            setMySelect3($('#buildNumber').val())
        }
    }
    const setMySelect3=(name)=>{
        //设置mySelect3
        myDataList3=myDataList2.find(item=> item.name==name)
        myDataList3=myDataList3.numberDOS
        //设置select
        $('#mySelect3').empty();
        $('#mySelect3').append($('<option>', {
            value: '',
            text: '请选择床号'
        }))
        myDataList3.forEach(item=>{
            $('#mySelect3').append($('<option>', {
                value: item.code,
                text: item.code,
                selected:$('#bedCode').val()==item.code
            }))
        })
        $('#mySelect3').attr("disabled",false);
        form.render('select');
        selectInput($('#mySelect3'),10)


    }
    $('#mySelect1').attr("disabled",true);
    AjaxGet( '/jzweb/jazHouseTypes/selHouseList'  ).then(function (response){
        if(response.code=='0'){
            myDataList1=response.data
            let newList=[]
            //

            myDataList1.forEach(item=>{
                if(newList.find(old=>old.name==item.name)){
                    newList=newList.map(item1 => {
                        if (item1.name === item.name) {
                            item1.buildNumberList.push({
                                name:item.buildNumber,
                                numberDOS:item.numberDOS
                            });
                        }
                        return item1;
                    });
                }else{
                    item.buildNumberList=[]
                    item.buildNumberList.push({
                        name:item.buildNumber,
                        numberDOS:item.numberDOS
                    })
                    newList.push(item)
                }
            })
            myDataList1=newList
            //对数据补充
            if($('#inputType').val()=='edit'){
                let communityName=$('#communityName').val()
                let buildNumber=$('#buildNumber').val()
                let bedCode=$('#bedCode').val()
                let bedNumberId=$('#bedNumberId').val()
                //新增小区名称
                if(!myDataList1.find(item=>item.name==communityName)){
                    myDataList1.push({
                        name:communityName,
                        buildNumberList:[]
                    })
                }
                //新增楼栋房号
                let _item=myDataList1.find(item=>item.name==communityName)
                if(!_item.buildNumberList.find(item=>item.name==buildNumber)){
                    myDataList1.map(item1 => {
                        if (item1.name === communityName) {
                            item1.buildNumberList.push({
                                name:buildNumber,
                                numberDOS:[]
                            });
                        }
                        return item1;
                    });
                }
                //新增床号
                _item=myDataList1.find(item=>item.name==communityName)
                let _item1=_item.buildNumberList.find(item=>item.name==buildNumber)
                if(!_item1.numberDOS.find(item=>item.id==bedNumberId)){
                    myDataList1.map(item1 => {
                        if (item1.name === communityName) {
                            item1.buildNumberList.map(item2=>{
                                if(item2.name===buildNumber){
                                    item2.numberDOS.push({
                                        id:bedNumberId,
                                        code:bedCode
                                    })
                                }
                                return item2;
                            })
                        }
                        return item1;
                    });
                }
            }
            //设置select
            $('#mySelect1').empty();
            $('#mySelect1').append($('<option>', {
                value: '',
                text: '请选择小区名称'
            }))
            myDataList1.forEach(item=>{
                $('#mySelect1').append($('<option>', {
                    value: item.name,
                    text: item.name,
                    selected:$('#communityName').val()==item.name
                }))
            })
            $('#mySelect1').attr("disabled",false);
            form.render('select');
            selectInput($('#mySelect1'),10)
            if($('#inputType').val()=='edit'){
                setMySelect2($('#communityName').val())
            }
        }
    }).catch(error => {
        layer.msg(error.msg)
    })
    form.on('select(demo-select-filter1)', function(data){
        if(data.value!=""){
            setMySelect2(data.value)
        }else{
            $('#mySelect2').empty();
            $('#mySelect2').append($('<option>', {
                value: '',
                text: '请选择小区名称'
            }))
            $('#mySelect3').empty();
            $('#mySelect3').append($('<option>', {
                value: '',
                text: '请选择楼栋房号'
            }))
            form.render('select');
        }
    })
    form.on('select(demo-select-filter2)', function(data){
        if(data.value!=""){
            setMySelect3(data.value)
        }else{
            $('#mySelect3').empty();
            $('#mySelect3').append($('<option>', {
                value: '',
                text: '请选择楼栋房号'
            }))
            form.render('select');
        }
    })

    form.on('radio(demo-radio-filter)', function(data){

        if(data?.elem?.value=='1'){
            $('#refuseReason').show()
        }else {
            $('#refuseReason').hide()
            $("textarea[name='refuseReason']").val('');
        }

    });
const getThisTime=(data=null)=>{
    if(null==data){
        data=new Date()
        data.setHours(data.getHours() + 1)
    }
    return data.getFullYear()+'-'+(data.getMonth()>9?(data.getMonth()+1):('0'+(data.getMonth()+1)))+'-'+data.getDate()+' '+data.getHours()+':00:00'
   }
    let startTimeDate='',endTimeDate='',oldTime=getThisTime()
    console.log('oldTime',oldTime)
    lay('.startTime').each(function () {
        startTimeDate=laydate.render({
            elem: this,
            type: 'datetime',
            trigger: 'click',
            max:$('.endTime').val()?$('.endTime').val():"9999-12-29",
            min:oldTime,
            ready: function(){
                $("span[lay-type='datetime']").click(()=>{

                    if($('.laydate-time-list>li').length==3){
                        let fen= $($('.laydate-time-list>li')[1]).find('li'),
                            miao=$($('.laydate-time-list>li')[2]).find('li')
                        for (let i = 0; i < fen.length; i++) {
                            $(fen[i]).attr('class', i==0?'layui-this':'laydate-disabled');
                        }
                        for (let i = 0; i < miao.length; i++) {
                            $(miao[i]).attr('class', i==0?'layui-this':'laydate-disabled');
                        }
                    }

                })

            },
            done: (value, dates) => {
                if(''==value){
                    $('#startTime').val()
                    let thisdate=new Date()
                    thisdate.setHours(thisdate.getHours() + 1);
                    endTimeDate.config.min = {
                        year: thisdate.getFullYear(),
                        month: thisdate.getMonth(), //关键
                        date: thisdate.getDate(),
                        hours: thisdate.getHours(),
                        minutes: '00',
                        seconds: '00'
                    };
                }else {
                    $('#startTime').val(dates.year+'-'+dates.month+'-'+ dates.date+' '+dates.hours+':00:00')
                    //+1
                    let thisdate=new Date(dates.year+'-'+dates.month+'-'+dates.date+' '+dates.hours+':00:00')
                    thisdate.setHours(thisdate.getHours() + 1);
                    endTimeDate.config.min = {
                        year: thisdate.getFullYear(),
                        month: thisdate.getMonth(), //关键
                        date: thisdate.getDate(),
                        hours: thisdate.getHours(),
                        minutes: '00',
                        seconds: '00'
                    };
                    // endTimeDate.config.min = {
                    //     year: dates.year,
                    //     month: dates.month - 1, //关键
                    //     date: dates.date,
                    //     hours: dates.hours,
                    //     minutes: '00',
                    //     seconds: '00'
                    // };
                }
            }
            // ,range: true
        });
    });
    lay('.endTime').each(function () {
        let oldstart=$('.startTime').val()
        let thisdate=new Date()
        thisdate.setHours(thisdate.getHours()+1)
        //空，加1
        if(!oldstart){
            thisdate.setHours(thisdate.getHours()+1)
        }
        let month=(thisdate.getMonth()+1)
        let thisdatestr=thisdate.getFullYear()+'-'+(month<10?('0'+month):month)+'-'+thisdate.getDate()+' '+thisdate.getHours()+':00:00'

        if(oldstart){
            console.log('oldstart111',oldstart)
            thisdate=new Date(oldstart)
            thisdate.setHours(thisdate.getHours()+1)
            month=(thisdate.getMonth()+1)
            oldstart=thisdate.getFullYear()+'-'+(month<10?('0'+month):month)+'-'+thisdate.getDate()+' '+thisdate.getHours()+':00:00'
            console.log('oldstart',oldstart)
        }
        endTimeDate=laydate.render({
            elem: this,
            type: 'datetime',
            trigger: 'click',
            min:$('.startTime').val()?oldstart:thisdatestr,
            ready: function(){
                $("span[lay-type='datetime']").click(()=>{
                    if($('.laydate-time-list>li').length==3){
                        let fen= $($('.laydate-time-list>li')[1]).find('li'),
                            miao=$($('.laydate-time-list>li')[2]).find('li')
                        for (let i = 0; i < fen.length; i++) {
                            $(fen[i]).attr('class', i==0?'layui-this':'laydate-disabled');
                        }
                        for (let i = 0; i < miao.length; i++) {
                            $(miao[i]).attr('class', i==0?'layui-this':'laydate-disabled');
                        }
                    }

                })

            },
            done: (value, dates) => {
                if(''==value){
                    $('#endTime').val()
                    startTimeDate.config.max = {
                        year: '3333',
                        month: '11', //关键
                        date: '30',
                        hours: '24',
                        minutes: '00',
                        seconds: '00'
                    };
                }else {
                   $('#endTime').val(dates.year + '-' + dates.month + '-' + dates.date + ' ' + dates.hours + ':00:00')
                    let mydata=new Date(dates.year + '-' + dates.month + '-' + dates.date + ' ' + dates.hours + ':00:00')
                    mydata.setHours(mydata.getHours() - 1)
                    let mymonth=mydata.getMonth()
                    startTimeDate.config.max = {
                        year:mydata.getFullYear(),
                        month: (mymonth<10?('0'+mymonth):mymonth), //关键
                        date: mydata.getDate(),
                        hours: mydata.getHours(),
                        minutes: '00',
                        seconds: '00'
                    };
                }
            }
        });
    });

    //提交事件
    form.on('submit(submit)', function (data) {
        if(!data.field.auditResult && $('#inputType').val()!='add'){
            layer.msg("请审核")
            return false
        }
        //拒绝过去
        if(data.field.auditResult!='1'||$('#inputType').val()=='add'){
            //提示
            if(data.field.mySelect1==''){
                layer.msg("请选择小区名称")
                return false
            }
            if(data.field.mySelect2==''){
                layer.msg("请选择楼栋房号")
                return false
            }
            if(data.field.mySelect3==''){
                layer.msg("请选择床号")
                return false
            }
        }else{
            if(data.field.refuseReason==''){
                layer.msg("请输入拒绝原因")
                return false
            }
        }
        let myDataList4=myDataList3.find((itemdata)=> itemdata.code==data.field.mySelect3)
        let mydata={
            sysUserid: myUser.sysUserid,
            username:myUser.name,
            sex:myUser.sex,
            phone:myUser.mobile,
            projectId:myUser.projectId,
            movieHouseTime1:data.field.checkTime,
            leaveTime1:data.field.endTime,
            communityName:data.field.mySelect1,
            buildNumber:data.field.mySelect2,
            bedCode:data.field.mySelect3,
            bedNumberId:myDataList4?.id,
            refuseReason:data.field.refuseReason,
            auditResult:data.field.auditResult
        }
        console.log(mydata,'===',data)
        let myUrl=''
        if($('#inputType').val()=='edit'){
            myUrl='/userHouse/updateHouse'
            mydata.id=$('#id').val()
        }else{
            myUrl='/userHouse/insertHouse'
        }
            AjaxPost(myUrl, mydata).then(function (response) {
                parent.layer.msg("操作成功");
                var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
                parent.layer.close(index);
                parent.load();
            }).catch(error => {
                layer.msg(error.msg)
            })

    });

});

